package com.example.bookmall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookmall.entity.Book;
import com.example.bookmall.entity.Category;
import com.example.bookmall.entity.Result;
import com.example.bookmall.mapper.BookMapper;
import com.example.bookmall.mapper.CategoryMapper;
import com.example.bookmall.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BookMapper bookMapper;

    //添加分类
    @Override
    @Transactional
    public Result addCategory(Category category) {
        // 获取分类名称并处理所有空格
        String categoryName = category.getCategoryName();
        if (categoryName == null) {
            return Result.error("分类名称不能为空");
        }

        // 移除所有空格（包括中间的空格）
        String cleanName = categoryName.replaceAll("\\s+", "");

        // 检查处理后的名称是否为空
        if (cleanName.isEmpty()) {
            return Result.error("分类名称不能为空");
        }

        // 将处理后的名称设置回分类对象
        category.setCategoryName(cleanName);

        // 检查处理后的名称是否已存在
        if (categoryMapper.selectOne(new QueryWrapper<Category>().eq("category_name", cleanName)) != null) {
            return Result.error("分类名称已存在");
        }

        int rows = categoryMapper.insert(category);
        return rows > 0 ? Result.success("添加成功") : Result.error("添加失败");
    }


    // 查询所有分类
    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectList(new QueryWrapper<>());
    }


    // 修改分类
    @Override
    @Transactional
    public Result updateCategory(Category category) {

        String categoryName = category.getCategoryName();
        // 移除所有空格（包括中间的空格）
        String cleanName = categoryName.replaceAll("\\s+", "");

        Category Iscategory = categoryMapper.selectOne(new QueryWrapper<Category>().eq("category_name", cleanName));

        if(Iscategory==null){
            categoryMapper.updateById(category);
            return Result.success("修改成功");
        }

        return Result.error("分类名称已存在");
    }

    // 删除分类
    @Override
    @Transactional
    public Result deleteCategory(Integer categoryId) {

        System.out.println("categoryId:"+categoryId);
        // 验证是否可以删除
        if (!canDeleteCategory(categoryId)) {
            return Result.error("分类下存在关联图书,无法删除");
        }

        int rows = categoryMapper.deleteById(categoryId);

        return rows > 0 ? Result.success("删除成功") : Result.error("删除失败");

    }

    @Override
    public Category getCategoryById(Integer categoryId) {
        return getById(categoryId);
    }

    // 根据名称查询分类列表
    @Override
    public List<Category> getCategoryByName(String categoryName) {
        if (categoryName == null) {
            return Collections.emptyList();
        }
        return categoryMapper.selectList(new QueryWrapper<Category>()
                .like("category_name", categoryName));
    }

    // 根据名称查询分类
    @Override
    public Category seCategoryByName(String categoryName) {

        return categoryMapper.selectOne(new QueryWrapper<Category>().eq("category_name", categoryName));
    }

    //  验证是否可以删除 分类下面是否关联图书
    public boolean canDeleteCategory(Integer categoryId) {
        // 检查是否存在关联图书
        long bookCount = bookMapper.selectCount(
                new QueryWrapper<Book>().eq("category_id", categoryId)
        );
        return bookCount == 0;
    }
}
